<?php use_helper('jQuery')?>
<?php use_stylesheets_for_form($form) ?>
<?php use_javascripts_for_form($form) ?>

<div id="main_header" class="ui-widget-header ui-corner-all">
    <?php if($form->getObject()->exists()):?>
        <h3>Editando Formulario: "<?php echo $form->getObject()->getTitle()?>"</h3>
    <?php else:?>
        <h3>Nuevo Formulario</h3>
    <?php endif;?>
</div>
<div id="main_content" class="ui-widget ui-widget-content ui-corner-all">
    <div class="form">
        <?php if ($form->getObject()->exists()): ?>
            <?php echo jq_form_remote_tag(
                    array (
                        'update'   => 'main',
                        'url'      => url_for('element_update',$form->getObject()),
                        'before'   => 'clearView();showLoaderMain();',
                        'complete' => 'hideLoader();',
                        'script'   => true,
                        'id'       => 'form_form'
                    ), array(
                        'id' => 'form_form'
                    )) ?>
            <input type="hidden" name="sf_method" value="put" />
        <?php else: ?>
            <?php echo jq_form_remote_tag(
                    array (
                        'update'   => 'main',
                        'url'      => url_for('element_create').'?type_id='.$type->getId().'&section_id='.$section->getId(),
                        'before' => 'clearView();showLoaderMain();',
                        'complete' => 'hideLoader();createTree();activateTreeMenu();',
                        'script' => true,
                        'method'   => 'post'
                    ), array(
                        'id' => 'form_form'
                    )) ?>
        <?php endif; ?>
            <fieldset>
                <?php echo $form->renderHiddenFields() ?>
                <?php echo $form->renderGlobalErrors() ?>
                <div class="form-row">
                    <?php echo $form['title']->renderLabel() ?>
                    <div class="form-field">
                        <?php echo $form['title']->renderError() ?>
                        <?php echo $form['title']->render() ?>
                    </div>
                </div>
                <div class="form-row">
                    <?php echo $form['Form']['uses_external_feed']->renderLabel() ?>
                    <div class="form-field">
                        <?php echo $form['Form']['uses_external_feed']->renderError() ?>
                        <?php echo $form['Form']['uses_external_feed']->render() ?>
                    </div>
                </div>
                <div class="form-row">
                    <?php echo $form['Form']['webservice_url']->renderLabel() ?>
                    <div class="form-field">
                        <?php echo $form['Form']['webservice_url']->renderError() ?>
                        <?php echo $form['Form']['webservice_url']->render() ?>
                    </div>
                </div>
                <?php foreach ($form['Form']['Fields'] as $i => $field): ?>
                    <fieldset id="<?php echo sprintf('field_%d', $i)?>" class="<?php echo ($i == 0 ? 'first' : '') ?>">
                        <legend>Campo</legend>
                        <div class="form-row">
                            <?php echo $field['title']->renderLabel() ?>
                            <div class="form-field">
                                <?php echo $field['title']->renderError() ?>
                                <?php echo $field['title']->render() ?>
                            </div>
                        </div>
                        <div class="form-row">
                            <?php echo $field['field_type_id']->renderLabel() ?>
                            <div class="form-field">
                                <?php echo $field['field_type_id']->renderError() ?>
                                <?php echo $field['field_type_id']->render() ?>
                            </div>
                            <?php echo jq_javascript_tag()?>
                                $('select#ems_element_Form_Fields_<?php echo $i ?>_field_type_id').change(
                                    function(){
                                        if($(this).val() == 10){
                                            $('div#options_field_<?php echo $i ?>').fadeIn("slow");
                                        } else {
                                            $('div#options_field_<?php echo $i ?>').fadeOut('slow',
                                                function(){
                                                    $(this).val('');
                                                }
                                            );
                                        }
                                    }
                                );
                            <?php echo jq_end_javascript_tag()?>
                        </div>
                        <div id="<?php echo 'options_field_'.$i ?>"
                             style="display: <?php echo ($form->getObject()->getForm()->getFields()->get($i)->getFieldType()->getType()=='Select' ? 'block' : 'none')?>">
                            <div class="form-row" >
                            <?php echo $field['options']->renderLabel() ?>
                            <div class="form-field">
                                <?php echo $field['options']->renderError() ?>
                                <?php echo $field['options']->render() ?>
                                <?php echo $field['options']->renderHelp() ?>

                            </div>
                        </div>
                        </div>
                        <div class="form-row">
                            <?php echo $field['is_key']->renderLabel() ?>
                            <div class="form-field">
                                <?php echo $field['is_key']->renderError() ?>
                                <?php echo $field['is_key']->render() ?>
                            </div>
                            <?php echo jq_javascript_tag()?>
                                $('input#ems_element_Form_Fields_<?php echo $i ?>_is_key').change(
                                    function(){
                                        if(this.checked){
                                            if($('input#ems_element_Form_Fields_<?php echo $i ?>_is_enabled').is(':checked')){
                                                $('input#ems_element_Form_Fields_<?php echo $i ?>_is_unique').attr('checked', true);
                                                $('input#ems_element_Form_Fields_<?php echo $i ?>_is_required').attr('checked', true);
                                                for(var i = 0; i < fields; i++ ){
                                                    if( i!=<?php echo $i ?> && $('input#ems_element_Form_Fields_'+i+'_is_key').is(':checked')){
                                                        alert('El campo "'+$('input#ems_element_Form_Fields_'+i+'_title').val()+'" esta marcado como clave, será desmarcado.\nSólo puede haber un campo clave.');
                                                        $('input#ems_element_Form_Fields_'+i+'_is_key').attr('checked', false);
                                                    }
                                                }
                                            } else {
                                                alert('Un campo deshabilitado no puede ser marcado como clave.\nHabilite el campo primero para poder ser marcardo como clave.');
                                                $(this).attr('checked', false);
                                            }
                                        } else {
                                            var key = false
                                            for(var i = 0; i < fields; i++ ){
                                                if(i!=<?php echo $i ?> && $("input#ems_element_Form_Fields_"+i+"_is_key").is(':checked')){
                                                    key = true
                                                }
                                            }
                                            if(!key){
                                                alert('Debe seleccionar al menos un campo como clave.');
                                            }
                                        }
                                    }
                                );
                            <?php echo jq_end_javascript_tag()?>
                        </div>
                        <div class="form-row">
                            <?php echo $field['is_unique']->renderLabel() ?>
                            <div class="form-field">
                                <?php echo $field['is_unique']->renderError() ?>
                                <?php echo $field['is_unique']->render() ?>
                            </div>
                            <?php echo jq_javascript_tag()?>
                                $('input#ems_element_Form_Fields_<?php echo $i ?>_is_unique').change(
                                    function(){
                                        if(!this.checked){
                                            if($('input#ems_element_Form_Fields_<?php echo $i ?>_is_key').is(':checked')){
                                                alert('El campo está marcado como clave, por lo tanto sus valores deben ser únicos.\nPara desmarcar esta característica primero desmarque la característica "Clave".');
                                                $(this).attr('checked', true);
                                            } else {
                                                alert('Este campo ahora admite valores duplicados.');
                                            }
                                        } else {
                                            $('input#ems_element_Form_Fields_<?php echo $i ?>_is_required').attr('checked', true);
                                        }
                                    }
                                );
                            <?php echo jq_end_javascript_tag()?>
                        </div>
                        <div class="form-row">
                            <?php echo $field['is_required']->renderLabel() ?>
                            <div class="form-field">
                                <?php echo $field['is_required']->renderError() ?>
                                <?php echo $field['is_required']->render() ?>
                            </div>
                            <?php echo jq_javascript_tag()?>
                                $('input#ems_element_Form_Fields_<?php echo $i ?>_is_required').change(
                                    function(){
                                        if(!this.checked){
                                            if($('input#ems_element_Form_Fields_<?php echo $i ?>_is_key').is(':checked')){
                                                alert('El campo está marcado como clave, por lo tanto su llenado es obligatorio.\nPara desmarcar esta característica primero desmarque las características "Clave y Único".');
                                                $(this).attr('checked', true);
                                            } else if($('input#ems_element_Form_Fields_<?php echo $i ?>_is_unique').is(':checked')){
                                                alert('El campo está marcado como único, por lo tanto su llenado es obligatorio sino podría tener valores nulos.\nPara desmarcar esta característica primero desmarque la característica "Único".');
                                                $(this).attr('checked', true);
                                            } else {
                                                alert('Este campo ahora admite valores nulos.');
                                            }
                                        }
                                    }
                                );
                            <?php echo jq_end_javascript_tag()?>
                        </div>
                        <?php if(isset ($field['is_enabled'])):?>
                            <div class="form-row">
                                <?php echo $field['is_enabled']->renderLabel() ?>
                                <div class="form-field">
                                    <?php echo $field['is_enabled']->renderError() ?>
                                    <?php echo $field['is_enabled']->render() ?>
                                </div>
                                <?php echo jq_javascript_tag()?>
                                $('input#ems_element_Form_Fields_<?php echo $i ?>_is_enabled').change(
                                    function(){
                                        if(!this.checked){
                                            if($('input#ems_element_Form_Fields_<?php echo $i ?>_is_key').is(':checked')){
                                                alert('Este campo está marcado como clave, será desmarcado.\nUn campo deshabilitado no puede ser clave,\n por favor indique cuál será el nuevo campo clave.');
                                                $('input#ems_element_Form_Fields_<?php echo $i ?>_is_key').attr('checked', false);
                                            }
                                        }
                                    }
                                );
                            <?php echo jq_end_javascript_tag()?>
                            </div>
                        <?php else: ?>
                            <?php if($i>0):?>
                                <a class="remove" href="#">Eliminar</a>
                            <?php endif;?>
                        <?php endif;?>
                    </fieldset>
                <?php endforeach; ?>
                <div id="extrafields"/>
                <div class="add-button">
                    <a class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-icon-primary"
                       id="add_field" href="#" aria-disabled="false">
                        <span class="ui-button-icon-primary ui-icon ui-icon-plusthick"></span>
                        <span class="ui-button-text">Agregar</span>
                    </a>
                </div>
                <div class="form-row">
                    <?php echo $form['position']->renderLabel() ?>
                    <div class="form-field">
                        <?php echo $form['position']->renderError() ?>
                        <?php echo $form['position']->render() ?>
                    </div>
                </div>
                <?php if(isset ($form['published']) && isset ($form['is_enabled'])):?>
                    <div class="form-row">
                        <?php echo $form['published']->renderLabel() ?>
                        <div class="form-field">
                            <?php echo $form['published']->renderError() ?>
                            <?php echo $form['published']->render() ?>
                        </div>
                    </div>
                    <div class="form-row">
                        <?php echo $form['is_enabled']->renderLabel() ?>
                        <div class="form-field">
                            <?php echo $form['is_enabled']->renderError() ?>
                            <?php echo $form['is_enabled']->render() ?>
                        </div>
                    </div>
                <?php endif;?>
            </fieldset>
            <div id="form_buttons" class="ui-widget">
                <input class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only ui-button-text"
                       type="submit" value="Guardar" title="Guardar"/>
                <?php if($form->getObject()->isNew()):?>
                    <?php echo jq_link_to_remote(
                        '<span class="ui-button-text">Cancelar</span>',
                        array(
                            'update' => 'main',
                            'url' => url_for('section_show', $form->getObject()->getSection()),
                            'before' => 'clearView();showLoaderMain();',
                            'complete' => 'hideLoader();',
                            'script' => true
                        ), array(
                            'class' => 'ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only',
                            'title' => 'Cancelar'
                        )) ?>
                <?php else: ?>
                    <?php echo jq_link_to_remote(
                            '<span class="ui-button-text">Cancelar</span>',
                        array(
                            'update' => 'main',
                            'url' => url_for('element_show',$form->getObject()),
                            'before' => 'clearView();showLoaderMain();',
                            'complete' => 'hideLoader();',
                            'script' => true
                        ), array(
                            'class' => 'ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only',
                            'title' => 'Cancelar'
                        )) ?>
                <?php endif; ?>
            </div>
        </form>
    </div>
</div>
<?php echo jq_javascript_tag()?>
    var fields =<?php echo $form['Form']['Fields']->count()?>;

    $().ready(
        function(){
            $('a#add_field').click(
                function() {
                    $('#extrafields').append(addField(fields));
                    fields = fields + 1;
                }
            );
        }
    );

    $().ready(
        function(){
            $('a.remove').click(
                function(){
                    removeField($(this).parent());
                }
            );
        }
    );

    $('#submit').click(
        function(event){
            event.preventDefault();
            if(checkKeySetup()){
                $('#form_form').submit();
            }
        }
    );

    function addField(num) {
        var r = $.ajax({
            type: 'POST',
            url: '<?php echo url_for('@element_addformfieldform'.(!$form->getObject()->isNew() ?
                            '?id='.$form->getObject()->getId().
                            '&num='
                        :
                            '?type_id='.$form->getObject()->getType()->getId().
                            '&num=')) ?>'+num,
            async: false}).responseText;
        return r;
    }

    function removeField(elem){
        $(elem).fadeOut('slow',
            function(){
                $(this).remove();
            }
        );
    }

    function checkKeySetup(){
        var key = false;
        for(var i = 0; i < fields; i++ ){
            if($('input#ems_element_Form_Fields_'+i+'_is_key').is(':checked')){
                key = true;
            }
        }
        if(!key){
            alert('No ha marcardo ningun campo como clave.\nIndique cual será el campo clave del formulario.');
        }
        return key;
    }
<?php jq_end_javascript_tag() ?>